package com.paul.girl.controller;

import com.paul.girl.domain.Girl;
import com.paul.girl.domain.Result;
import com.paul.girl.service.GirlService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

import static com.paul.girl.utils.ResultUtil.failed;
import static com.paul.girl.utils.ResultUtil.success;

@RestController
public class GirlController {
    @Autowired
    private GirlService service;
    private final static Logger logger = LoggerFactory.getLogger(GirlController.class);


    @GetMapping("girls")
    public List<Girl> girlList() {
        System.out.println("girlList()方法执行了");
        return service.findGirls();
    }

    @PostMapping("girls")
    public Result<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            return failed(bindingResult.getFieldError().getDefaultMessage(), 1);
        }
        return success(girl);
    }

    @GetMapping("girls/{id}")
    public Girl findGirl(@PathVariable("id") String id) {
        return service.findGirl(id);
    }

    @PutMapping("girls/{id}")
    public void updateGirl(@PathVariable("id") String id, Girl girl) {
        service.updateGirl(girl, id);
    }

    @DeleteMapping("girls/{id}")
    public void deleteGirl(@PathVariable("id") String id) {
        service.deleteGirl(id);
    }

    //根据年龄查女生
    @GetMapping("girls/age/{age}")
    public List<Girl> girlListByAge(@PathVariable("age") String age){
             return service.findByAge(Integer.parseInt(age));
    }

    //根据id快速查年龄
    @GetMapping("girls/getAge/{id}")
    public Integer getAge(@PathVariable("id") String id){
        return service.getAge(id);
    }

}
